﻿using Helpers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.Extensions.Hosting
{
    public static class DiExtensions
    {
        /// <summary>
        /// 初始化全局DiHelper单例,会创建一个新的IServiceProvider
        /// </summary>
        public static IServiceCollection AddDiHelper(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            //自动注入
            var types = DiHelper.GetTypes(typeof(ISingleton));
            if (types?.Count() > 0)
            {
                foreach (var item in types)
                {
                    if (typeof(ISingleton).IsAssignableFrom(item))
                    {
                        services.AddSingleton(item);
                    }
                }
                Console.WriteLine($"注册单例--{string.Join(",", types.Select(x => x.Name))}");
            }

            return DiHelper._services = services;
        }

        /// <summary>
        /// 初始化全局DiHelper单例,并在启动时自动执行IStartupTask注册的服务,用在program.cs
        /// </summary>
        public static async Task RunWithDiHelperAsync(this IHost host, CancellationToken cancellationToken = default)
        {
            DiHelper._serviceProvider = host.Services;
            //注册中文编码
            DiHelper.EncodingRegisterProvider();

            //执行IStartupTask
            var startupTasks = host.Services.GetServices<IStartupTask>();
            foreach (var startupTask in startupTasks)
            {
                await startupTask.ExecuteAsync(cancellationToken);
            }

            await host.RunAsync(cancellationToken);
        }
    }
}
